import {Inject, Injectable} from "@nestjs/common";
import {StaffRelateTags, StaffSaveDto} from "~/modules/consult/staff/staff.dto";
import {InjectRepository} from "@nestjs/typeorm";
import {Repository} from "typeorm";
import {StaffEntity} from "~/modules/consult/staff/staff.entity";
import {UploadService} from "~/modules/tools/upload/upload.service";
import {StaffTagEntity} from "~/modules/consult/tag/tag.entity";

@Injectable()
export class StaffService {
  @InjectRepository(StaffEntity)
  private readonly staffRepository: Repository<StaffEntity>
  @InjectRepository(StaffTagEntity)
  private readonly tagRepository: Repository<StaffTagEntity>
  @Inject()
  private readonly uploadService: UploadService

  async save(staffSaveDto: StaffSaveDto) {
    const path: string = await this.uploadService.saveFile(staffSaveDto.file)

    const staff = new StaffEntity()
    staff.name = staffSaveDto.name
    staff.avatar = path
    staff.description = staffSaveDto.description
    staff.mobile = staffSaveDto.mobile
    staff.score = staffSaveDto.score

    return await this.staffRepository.save(staff)
  }

  async remove(id: number) {
    // 先查询是否存在
    const goods = await this.staffRepository.findOne({where: {id}})

    // 删除图片图片
    await this.uploadService.removeFile(goods.avatar)
    await this.staffRepository.delete(id)
  }

  async find() {
    // return await this.staffRepository.find()
    // 将关联的标签一起查出来
    return await this.staffRepository.find({relations: ['tags']})
  }

  async relate(staffRelateTags: StaffRelateTags) {
    // Retrieve the Staff entity
    const staff = await this.staffRepository.findOne({
      where: {id: staffRelateTags.staffId},
      relations: ['tags'], // Ensure to load existing tags to avoid overwriting them
    });

    if (!staff) {
      throw new Error('Staff not found');
    }

    // Retrieve Tag entities
    const tagEntities = await this.staffRepository
      .createQueryBuilder('staff')
      .relation(StaffEntity, 'tags')
      .of(staff) // You can pass the staff entity directly
      .loadMany();

    // Assuming `tags` is an array of tag IDs
    const newTagEntities = await Promise.all(
      staffRelateTags.tags.map(tagId =>
        this.tagRepository.findOne({where: {id: tagId}})
      )
    );

    // Filter out any null values in case some tags were not found
    const validTags = newTagEntities.filter(tag => tag !== undefined);

    // Associate Tags with Staff
    staff.tags = [...tagEntities, ...validTags];

    // Save the updated Staff entity
    await this.staffRepository.save(staff);
  }

	// 取消关联
	async unRelate(staffId: number, tagIds: number[]) {
		// Retrieve the Staff entity
		const staff = await this.staffRepository.findOne({
			where: {id: staffId},
			relations: ['tags'], // Ensure to load existing tags to avoid overwriting them
		});

		if (!staff) {
			throw new Error('Staff not found');
		}

		// Retrieve Tag entities
		const tagEntities = await this.staffRepository
			.createQueryBuilder('staff')
			.relation(StaffEntity, 'tags')
			.of(staff) // You can pass the staff entity directly
			.loadMany();

		// Assuming `tags` is an array of tag IDs
		const newTagEntities = await Promise.all(
			tagIds.map(tagId =>
				this.tagRepository.findOne({where: {id: tagId}})
			)
		);

		// Filter out any null values in case some tags were not found
		const validTags = newTagEntities.filter(tag => tag !== undefined);

		// Associate Tags with Staff
		staff.tags = tagEntities.filter(tag => !validTags.includes(tag));

		// Save the updated Staff entity
		await this.staffRepository.save(staff);
	}
}
